"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 二级分区
Case Name   : 二级分区表行访问控制
Create At   : 2022/2/26
Owner       : @daiguatutu
Description :
    1.创建表空间和2个用户
    2.创建一级和二级分区表
    3.插入数据
    4.将表的读取权限赋予用户1和用户2
    5.打开行访问控制策略开关
    6.创建行访问控制策略，当前用户只能查看用户自身的数据
    7.查看表相关信息
    8.当前用户执行select操作
    9.给用户登录权限
    10.切换至用户1执行select操作
    11.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.合理报错
    6.合理报错
    7.成功，无row level security policies
    8.成功
    9.成功
    10.成功
    11.清理成功
History     :
"""
import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class Subpartition(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.primaryNode = Node('PrimaryDbUser')
        self.constant = Constant()
        self.t_name = 't_subpartition_0356'
        self.ts_name = 'ts_subpartition_0356'
        self.r_name1 = 'r_subpartition_0356_01'
        self.r_name2 = 'r_subpartition_0356_02'

    def test_subpartition(self):
        text = '-----step1:创建表空间和用户 expect:成功-----'
        self.log.info(text)
        create_sql = f"drop table if exists {self.t_name};" \
            f"drop role if exists {self.r_name1},{self.r_name2};" \
            f"drop tablespace if exists {self.ts_name};" \
            f"create tablespace {self.ts_name} relative location " \
            f"'{self.ts_name}';" \
            f"create role {self.r_name1} password '{macro.COMMON_PASSWD}';" \
            f"create role {self.r_name2} password '{macro.COMMON_PASSWD}';"
        msg = self.pri_sh.execut_db_sql(create_sql)
        self.log.info(msg)
        self.assertIn(self.constant.TABLESPCE_CREATE_SUCCESS, msg,
                      '执行失败:' + text)
        self.assertEqual(2, msg.count(self.constant.CREATE_ROLE_SUCCESS_MSG),
                         '执行失败:' + text)

        text = '-----step2:创建一级和二级分区表 expect:成功-----'
        self.log.info(text)
        create_sql = f"drop table if exists {self.t_name};" \
            f"create table {self.t_name} (id int, role varchar(100), " \
            f"data varchar(100))tablespace {self.ts_name}; " \
            f"drop table if exists {self.t_name};" \
            f"create table {self.t_name} (id int, role varchar(100), " \
            f"data varchar(100))tablespace {self.ts_name} " \
            f"partition by range (id) subpartition by hash (role) " \
            f"(partition p_range_1 values less than(-10) " \
            f"(subpartition p_hash_1_1,subpartition p_hash_1_2," \
            f"subpartition p_hash_1_3)," \
            f"partition p_range_2 values less than(20)," \
            f"partition p_range_3 values less than(30) " \
            f"(subpartition p_hash_3_1,subpartition p_hash_3_2," \
            f"subpartition p_hash_3_3)," \
            f"partition p_range_4 values less than(50)" \
            f"(subpartition p_hash_4_1,subpartition p_hash_4_2," \
            f"subpartition p_hash_4_3)," \
            f"partition p_range_5 values less than(maxvalue));"
        msg = self.pri_sh.execut_db_sql(create_sql)
        self.log.info(msg)
        self.assertEqual(2, msg.count(self.constant.DROP_TABLE_SUCCESS),
                         '执行失败:' + text)
        self.assertEqual(2, msg.count(self.constant.CREATE_TABLE_SUCCESS),
                         '执行失败:' + text)

        text = '-----step3:插入数据 expect:成功-----'
        self.log.info(text)
        sql = f"insert into {self.t_name} values" \
            f"(1, '{self.r_name1}', '{self.r_name1} data')," \
            f"(2, '{self.r_name2}', '{self.r_name2} data')," \
            f"(3, 'peter', 'peter data');"
        msg = self.pri_sh.execut_db_sql(sql)
        self.log.info(msg)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, msg, '执行失败:' + text)

        text = '-----step4:将表的读取权限赋予2个新建用户 expect:成功-----'
        self.log.info(text)
        sql = f"grant select on {self.t_name} to {self.r_name1}, " \
            f"{self.r_name2};"
        msg = self.pri_sh.execut_db_sql(sql)
        self.log.info(msg)
        self.assertIn(self.constant.GRANT_SUCCESS_MSG, msg, '执行失败:' + text)

        text = '-----step5:打开行访问控制策略开关; expect:合理报错-----'
        self.log.info(text)
        sql = f"alter table {self.t_name} enable row level security;"
        msg = self.pri_sh.execut_db_sql(sql)
        self.log.info(msg)
        self.assertIn('Un-support feature', msg, '执行失败:' + text)

        text = '-----step6:创建行访问控制策略，当前用户只能查看用户自身的数据; expect:合理报错-----'
        self.log.info(text)
        sql = f"create row level security policy {self.t_name}_rls on " \
            f"{self.t_name} using(role = current_user);"
        msg = self.pri_sh.execut_db_sql(sql)
        self.log.info(msg)
        self.assertIn('Un-support feature', msg, '执行失败:' + text)

        text = '-----step7:查看表相关信息; ' \
               'expect:成功，无row level security policies-----'
        self.log.info(text)
        msg = self.pri_sh.execut_db_sql(f'\d+ {self.t_name}')
        self.log.info(msg)
        self.assertNotIn('row level security policies', msg, '执行失败:' + text)

        text = '-----step8:当前用户执行select操作; expect:成功-----'
        self.log.info(text)
        select_sql = f"select * from {self.t_name};"
        msg = self.pri_sh.execut_db_sql(select_sql)
        self.log.info(msg)
        self.assertIn('3 rows', msg, '执行失败:' + text)

        text = '-----step9:给用户登录权限; expect:成功-----'
        self.log.info(text)
        sql = f"alter user {self.r_name1} login;"
        msg = self.pri_sh.execut_db_sql(sql)
        self.log.info(msg)
        self.assertIn(self.constant.ALTER_ROLE_SUCCESS_MSG, msg,
                      '执行失败:' + text)

        text = '-----step10:切换至用户1执行select操作; expect:成功-----'
        self.log.info(text)
        cmd = f"source {macro.DB_ENV_PATH};" \
            f"gsql -d {self.primaryNode.db_name} " \
            f"-p {self.primaryNode.db_port} -c '{select_sql}' " \
            f"-U {self.r_name1} -W '{macro.COMMON_PASSWD}';"
        self.log.info(cmd)
        msg = self.primaryNode.sh(cmd).result()
        self.log.info(msg)
        self.assertIn('3 rows', msg, '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----step11:清理环境-----')
        text_1 = '-----删除表,表空间，用户 expect:成功-----'
        self.log.info(text_1)
        del_cmd = f'drop table if exists {self.t_name};' \
            f'drop role if exists {self.r_name1},{self.r_name2};' \
            f'drop tablespace if exists {self.ts_name};'
        del_msg = self.pri_sh.execut_db_sql(del_cmd)
        self.log.info(del_msg)

        self.assertIn(self.constant.TABLESPCE_DROP_SUCCESS, del_msg,
                      '执行失败:' + text_1)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, del_msg,
                      '执行失败:' + text_1)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, del_msg,
                      '执行失败:' + text_1)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
